﻿namespace ET
{
    public class UnitAwakeSystem : AwakeSystem<Unit,int>
    {
        public override void Awake(Unit self,int id)
        {
#if SERVER
            //建立循环任务，每5分钟保存一次数据
            self.Timer = TimerComponent.Instance.NewRepeatedTimer(300000, self.InitUnitSaveDB);
#endif
        }
    }
    
    public class UnitDestorySystem : DestroySystem<Unit>
    {
        public override void Destroy(Unit self)
        {
#if SERVER
            TimerComponent.Instance.Remove(ref self.Timer);
#endif
        }
    }
    
    public static class UnitSystem
    {
        public static async void InitUnitSaveDB(this Unit self)
        {
#if SERVER
            await self.SaveDB();
#endif
            await ETTask.CompletedTask;
        }
        public static void UpdateGold(this Unit unit,int count)
        {
            unit.GetComponent<TCharacter>().Gold += count;
#if SERVER
            
#else
            Game.EventSystem.Publish(new EventType.UpdateDynamicAttr() {ZoneScene = unit.DomainScene()});
#endif
        }

        public static void UpdateGem(this Unit self, int count)
        {
            self.GetComponent<TCharacter>().Gem += count;
#if SERVER
#else
            Game.EventSystem.Publish(new EventType.UpdateDynamicAttr() {ZoneScene = self.DomainScene()});
#endif
        }

        public static async ETTask SaveDB(this Unit self)
        {
#if SERVER
            DBComponent db = self.Domain.GetComponent<DBComponent>();
            if (self.IsDisposed) return;

            await db.Save(self.GetComponent<BagComponent>());
            await db.Save(self.GetComponent<EquipComponent>());
            await db.Save(self.GetComponent<TCharacter>());

            await DBHelper.UpdateCacheDB(self);
#endif
            await ETTask.CompletedTask;
        }
    }
}